package com.example.demo.controller;

import com.example.demo.DemoApplication;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

/**
 * @author 杜科
 * @description
 * @contact 15521177704
 * @since 2019/10/14
 */
@RestController
public class controller {

    @Autowired
    RedissonClient redissonClient;

    @GetMapping("/get")
    public void get(){

        Jedis jedis= DemoApplication.jedis;
        Integer sum=Integer.valueOf(jedis.get("apple"));
        RLock lock = redissonClient.getLock("appleLock");
        System.out.println("sum: " + sum);
        try {
            //加锁 操作很类似Java的ReentrantLock机制
            lock.lock();
            if(sum>0) {
                sum--;
                jedis.set("apple",String.valueOf(sum));
                System.out.println("succeed!remain: " +jedis.get("apple"));
            }
            else System.out.println("failed");

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            //解锁
            lock.unlock();
        }

    }
}
